/**
 * 添加或者修改页面
 */
var ToolWaveInfoDlg = {
    data: {
        waveName: "",
        nodes: "",
        v1: "",
        v2: "",
        v3: "",
        v4: "",
        deptId: "",
        deliverId: "",
        createTime: "",
        createUserName: ""
    }
};
/**
 * 详情对话框
 */
var ToolTaskArrangeInfoDlg = {
    data: {
        groupNumber: "",
        groupUsers: ""
    }
};
var submit = 0
layui.use(['form', 'admin', 'ax','laydate','element','table'], function () {
    var $ = layui.jquery;
    var table = layui.table;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laydate = layui.laydate;
	var element = layui.element
	
	//tab切换
	element.on('tab(doTabBrief)',function(data){
		console.log(data.index)
	})

    //让当前iframe弹层高度适应
    admin.iframeAuto();
    
    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
    	var msg;
        $.ajax({
        	url:Feng.ctxPath + "/toolWork/addItem?waveId="+Feng.getUrlParam("waveId"),
			data:data.field,
        	cache: false,
        	dataType:"json",
        	beforeSend:function(){
        		msg = layer.msg('提交中。。。请耐心等待', {
        			  icon: 16,
        			  shade: [0.2,'#000'], //0.1透明度的白色背景
        			  time: false
        		});
        	},
        	success:function(data){
            	layer.close(msg); 
        		if (data.success) {
                	Feng.success("操作成功！波次自动+1");
					var wellen = $("#wellen").val()
					$("#wellen").val((wellen*1)+1)
					$("#orderNumber").val("")
                	table.reload(ToolWork2.tableId);
				} else {
    				var msg2 =  layer.open({
	  					  title: '提示' ,
	  					  content: data.message,
	  					  btn: ['确定'],
	  					  yes: function (){
	  						  	layer.close(msg2);
	  					  }
    				}); 
				}
        	},
        	error:function(data){
            	layer.close(msg); 
                Feng.error("操作失败！" + data.responseJSON.message)
        	}
        })

        return false;
    });
    
    //表单提交事件
    form.on('submit(btnSubmitWellen)', function (data) {
    	var msg;
        $.ajax({
        	url:Feng.ctxPath + "/toolWork/saveItem?waveId="+Feng.getUrlParam("waveId"),
			data:data.field,
        	cache: false,
        	dataType:"json",
        	beforeSend:function(){
        		msg = layer.msg('提交中。。。请耐心等待', {
        			  icon: 16,
        			  shade: [0.2,'#000'], //0.1透明度的白色背景
        			  time: false
        		});
        	},
        	success:function(data){
            	layer.close(msg); 
        		if (data.success) {
                	Feng.success("操作成功！波次自动+1");
					var wellen = $("#wellen").val()
					$("#wellen").val((wellen*1)+1)
					$("#orderNumber").val("")
                	table.reload(ToolWork2.tableId);
				} else {
    				var msg2 =  layer.open({
	  					  title: '提示' ,
	  					  content: data.message,
	  					  btn: ['确定'],
	  					  yes: function (){
	  						  	layer.close(msg2);
	  					  }
    				}); 
				}
        	},
        	error:function(data){
            	layer.close(msg); 
                Feng.error("操作失败！" + data.responseJSON.message)
        	}
        })

        return false;
    });

    //点击选择小组
    $('#selectArrange').click(function () {
		var positionNumber = $("input[name='arrangeNumber']:checked").val();
    	submit = 0
        layer.open({
            type: 2,
            title: '选择小组',
            area: ['700px', '400px'],
            content: Feng.ctxPath + '/toolWave/toselectArrange2?waveId='+Feng.getUrlParam("waveId")+"&groupNumber="+positionNumber,
            end: function () {
            	if(submit == 1){
                	$("#userName").val(ToolTaskArrangeInfoDlg.data.groupUsers);//小组人员
            	}
            }
        });
    });

    //返回按钮
    $("#backupPage").click(function () {
        window.location.href = Feng.ctxPath + '/toolWave'
    });

    //返回按钮
    $("#backupPage1").click(function () {
        window.location.href = Feng.ctxPath + '/toolWave'
    });

    //返回按钮
    $("#backupPage2").click(function () {
        window.location.href = Feng.ctxPath + '/toolWave'
    });

    //返回按钮
    $("#backupPage3").click(function () {
        window.location.href = Feng.ctxPath + '/toolWave'
    });

    var ToolWork2 = {
        tableId: "toolWorkTable2"
    };

    var ToolExpress3 = {
        tableId: "toolExpressTable3"
    };

    ToolWork2.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {align: 'center', toolbar: '#tableBar2', title: '操作', width:240},
            {field: 'state', sort: true, title: '状态', templet: '#billstateTpl'},
            {field: 'customerName', sort: true, title: '客户'},
            {field: 'wellen', sort: true, title: '波次'},
            {field: 'arrangeNumber', sort: true, title: '小组编号'},
            {field: 'userName', title: '小组人员'},
            {field: 'addTask', title: '生成补货任务'},
            {field: 'handover', title: '交接次数'},
            {field: 'direct', sort: true, title: '是否直贴'},
            {field: 'packNumber', title: '包材编号'},
            {field: 'createTime', title: '创建时间'},
            {field: 'createName', title: '操作人员'},
        ]];
    };
    
    /**
     * 初始化表格的列
     */
    ToolExpress3.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {field: 'customerName', sort: true, title: '客户'},
            {field: 'wellen', sort: true, title: '波次'},
            {field: 'v1', sort: true, title: '出库单号'},
            {field: 'orderNumber', sort: true, title: '快递单号'},
            {field: 'goodsNumber', sort: true, title: '商品组合', totalRowText: '合计：'},
            {field: 'num', sort: true, title: '组合数量', totalRow: true},
            {field: 'v2', sort: true, title: '重量', totalRow: true},
            {field: 'v3', sort: true, title: '快递公司'},
            {field: 'v4', sort: true, title: '省份'},
            {field: 'v5', sort: true, title: '城市'},
            {field: 'v6', sort: true, title: '区县'},
            {field: 'v7', sort: true, title: '街道'},
            {field: 'v8', sort: true, title: '地址'},
        ]];
    };
    
    // 单击行事件
    table.on('row(' + ToolWork2.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + ToolWork2.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + ToolWork2.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6;" });//改变当前tr颜色
    });
    
    // 单击行事件
    table.on('row(' + ToolExpress3.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + ToolExpress3.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + ToolExpress3.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6;" });//改变当前tr颜色
    });

    // 渲染表格
    var tableResult2 = table.render({
        elem: '#' + ToolWork2.tableId,
        url: Feng.ctxPath + '/toolWork/list?waveId='+Feng.getUrlParam("waveId"),
        page: true,
        limit: 120,
        height: "full-60",
        toolbar: '#toolbarfrom',
		limits:[120,240,480,1020],
        cellMinWidth: 100,
        cols: ToolWork2.initColumn()
    });

    // 渲染表格
    var tableResult3 = table.render({
        elem: '#' + ToolExpress3.tableId,
        url: Feng.ctxPath + '/toolExpress/list?waveId='+Feng.getUrlParam("waveId"),
        page: true,
        limit: 120,
        height: "full-60",
        totalRow: true,
        toolbar: '#toolbarfrom',
		limits:[40,60,120,240,360,480,1500,3000,6000,9000],
        cellMinWidth: 100,
        cols: ToolExpress3.initColumn()
    });
    
    /**
     * 点击查询按钮
     */
    ToolWork2.search = function () {
        var queryData = {};
        queryData['customerId'] = $("#customerId2").val();
        queryData['arrangeNumber'] = $("#arrangeNumber2").val();
        queryData['wellen'] = $("#wellen2").val();
        table.reload(ToolWork2.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };
	    
    /**
     * 点击查询按钮
     */
    ToolExpress3.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition3").val();
        queryData['customerId'] = $("#customerId3").val();
        queryData['wellen'] = $("#wellen3").val();
        queryData['v1'] = $("#v13").val();
        queryData['v2'] = $("#v23").val();
        queryData['goodsNumber'] = $("#goodsNumber3").val();
        table.reload(ToolExpress3.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };

    // 搜索按钮点击事件
    $('#btnSearch2').click(function () {
        ToolWork2.search();
    });

    // 搜索按钮点击事件
    $('#btnSearch3').click(function () {
        ToolExpress3.search();
    });
    
    /**
     * 导出excel按钮
     */
    ToolExpress3.exportExcel = function () {
        var checkRows = table.checkStatus(ToolExpress3.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult3.config.id, checkRows.data, 'xls');
        }
    };
		
    // 导出excel
    $('#btnExp3').click(function () {
        ToolExpress3.exportExcel();
    });
		
	//批量复制    
    $('#copyOrder3').click(function () {
    	var checkStatus = table.checkStatus('toolExpressTable3');
        data = checkStatus.data;
        if (data.length>0) {
			var orders = "";
            for (var i = 0; i < data.length; i++) {
				orders += data[i].orderNumber;
				orders += "\n";
			}
			// 获取要复制的文本
			const textToCopy = orders;
			
			// 创建一个临时的textarea元素，并将文本内容设置为要复制的文本
			const tempTextarea = document.createElement("textarea");
			tempTextarea.value = textToCopy;
			
			// 将textarea添加到DOM中
			document.body.appendChild(tempTextarea);
			
			// 选中textarea中的文本
			tempTextarea.select();
			
			// 执行复制命令
			document.execCommand("copy");
			
			// 删除临时创建的textarea元素
			document.body.removeChild(tempTextarea);
			
        	Feng.success("复制成功!");
		} else {
			layer.alert('请至少选中一条数据');
		}
    });
	    
    // 批量派工
    $('#btnPaigong2').click(function () {
    	var checkStatus = table.checkStatus('toolWorkTable2');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
				if(data[i].state != '待派工'){
		    		layer.msg('请选择待派工波次'); 
					return
				}
            	ids.push(data[i].id);
			}
        	submit = 0
	        layer.open({
	            type: 2,
	            title: '批量派工',
	            area: ['850px', '500px'],
	            anim: 5,
	            content: Feng.ctxPath + '/toolWork/choice_user?ids='+ids+"&waveId="+Feng.getUrlParam("waveId"),
	            end: function () {
	            	if(submit == 1){
	                	table.reload(ToolWork2.tableId);
	            	}
	            }
	        });
		} else {
			layer.alert('请至少选中一条数据');
		}
    });
	    
    table.on('tool(' + ToolWork2.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit2'){
        	submit = 0
	        layer.open({
	            type: 2,
	            title: '修改派工',
	            area: ['850px', '500px'],
	            anim: 5,
	            content: Feng.ctxPath + '/toolWork/editWellen?id='+data.id+"&waveId="+data.waveId,
	            end: function () {
	            	if(submit == 1){
                		table.reload(ToolWork2.tableId);
	            	}
	            }
	        });
		} else if (layEvent === 'delete2') {
	        var operation = function () {
	            var ajax = new $ax(Feng.ctxPath + "/toolWork/delete", function (data) {
	                Feng.success("删除成功!");
	                table.reload(ToolWork2.tableId);
	            }, function (data) {
	                Feng.error("删除失败!" + data.responseJSON.message + "!");
	            });
            	ajax.set("id", data.id);
	            ajax.start();
	        };
	        Feng.confirm("是否删除?", operation);
		} else if (layEvent === 'mingxi2') {
	        layer.open({
	            type: 2,
	            title: '单号列表',
	            area: ['850px', '500px'],
	            anim: 5,
	            content: Feng.ctxPath + '/toolExpress/mingxi?waveId='+data.waveId+"&wellen="+data.wellen,
	            end: function () {
	            }
	        });
		} else if (layEvent === 'paigong2') {
			if(data.state != '待派工'){
	    		layer.msg('请选择待派工波次'); 
				return
			}
            var ids = [];
        	ids.push(data.id);
        	submit = 0
	        layer.open({
	            type: 2,
	            title: '派工',
	            area: ['850px', '500px'],
	            anim: 5,
	            content: Feng.ctxPath + '/toolWork/choice_user?ids='+ids+"&waveId="+Feng.getUrlParam("waveId"),
	            end: function () {
	            	if(submit == 1){
	                	table.reload(ToolWork2.tableId);
	            	}
	            }
	        });
		}
    });


















});